package com.wu.wechat.controller;

import com.wu.common.staticpack.Weixin;
import com.wu.common.utils.OConvertUtils;
import com.wu.common.utils.Result;
import com.wu.entity.weixin.po.MyJwWebJwid;
import com.wu.entity.weixin.po.WeixinGzuser;
import com.wu.wechat.resp.TextMessageResp;
import com.wu.wechat.service.MyJwWebJwidService;
import com.wu.wechat.service.WechatService;
import com.wu.wechat.util.MessageUtil;
import com.wu.wechat.util.SignUtil;
import com.wu.common.utils.WeixinUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 微信客户端，请求处理核心类
 * @author zhangdaihao
 *
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {
	public final static Logger log = LoggerFactory.getLogger(WechatController.class);
	
	@Autowired
	private WechatService wechatService;
	@Resource
	private MyJwWebJwidService myJwWebJwidService;

	@RequestMapping(value = "/auth", method = RequestMethod.GET)
	public void wechatGet(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
		
		log.info("-------------------微信公众号响应消息------------wechatGet------");
		List<MyJwWebJwid> myJwWebJwids = myJwWebJwidService.queryAll();
		// 获取随机数
		String echostr = request.getParameter("echostr");
		// 加密签名
		String signature = request.getParameter("signature");
		//随机数
		String nonce = request.getParameter("nonce");
		//时间戳
		String timestamp = request.getParameter("timestamp");
		if(myJwWebJwids != null && myJwWebJwids.size() > 0) {
			log.info("--------------myJwWebJwids------------size------" + myJwWebJwids.size());
			for (MyJwWebJwid myJwWebJwid : myJwWebJwids) {
				if(SignUtil.checkSignature(myJwWebJwid.getToken(), signature, timestamp, nonce)) {
					try {
						response.getWriter().print(echostr);
						break;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@RequestMapping(value = "/auth", method = RequestMethod.POST)
	public void wechatPost(HttpServletResponse response,
                           HttpServletRequest request) throws IOException {
		log.info("------------------微信公众号响应消息-------------wechatPost-----");
		String respMessage = null;
		try {
			respMessage = wechatService.coreService(request);
		} catch (Exception e) {
			e.printStackTrace();
			if(OConvertUtils.isEmpty(respMessage)){
				respMessage = getWeixinMsg(request);
			}
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.close();
	}


	@RequestMapping(value = "/getInfoByCode", method = RequestMethod.POST)
	@ResponseBody
	public Result getInfoByCode(@RequestParam("code") String code) throws IOException {

		MyJwWebJwid entity = myJwWebJwidService.queryByJwid(Weixin.weixinId);

		log.info("------------------微信公众号获取用户信息-------------code-----");
		String requestUrl = WeixinUtil.web_oauth_accesstoken_url.replace("CODE", code)
				.replace("APPID",entity.getWeixinAppId())
				.replace("SECRET",entity.getWeixinAppSecret());
		JSONObject obj = new JSONObject();
		JSONObject jsonList = WeixinUtil.httpRequest(requestUrl, "GET", obj.toString());
		log.info("------------调用接口返回------------:  "+jsonList.toString());
		if(StringUtils.isNotEmpty(jsonList.getString("openid"))){
			WeixinGzuser res = wechatService.saveInfoByCode(jsonList,entity);
			return Result.ok(res);
		}
		return Result.error();
	}
	
	
	/**
	 * 异常情况下，回复此消息
	 * @param request
	 * @return
	 */
	private String getWeixinMsg(HttpServletRequest request){
		// 异常情况下，回复此文本消息
		TextMessageResp textMessage = new TextMessageResp();
		try {
			// 默认返回的文本消息内容
			String respContent = "系统网络繁忙，请稍后再试！";
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			//消息id
			String msgId = requestMap.get("MsgId");
			//消息内容
			String content = requestMap.get("Content");
			//多媒体ID
			String mediaId = requestMap.get("MediaId");
			
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			//textMessage.setCreateTime(new Date().getTime());
			textMessage.setCreateTime(System.currentTimeMillis());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setContent(respContent);
		} catch (Exception e) {
		}
		// 将文本消息对象转换成xml字符串
		return MessageUtil.textMessageToXml(textMessage);
	}

}
